<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1000">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="姓名" prop="patientName">
            <el-input v-model="formData.patientName" placeholder="患者姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input 
              v-model="formData.idNumber" 
              placeholder="请输入身份证号" 
              :disabled="formType === 'action.edit'" 
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" placeholder="请选择性别" clearable>
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.GENDER)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="评定的风险等级" prop="riskAssessment" label-width="150px">
            <el-input v-model="formData.riskAssessment" placeholder="请输入评定的风险等级" />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="formType === 'action.add'">
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker type="date" v-model="formData.birthDate" :clearable="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="监护人" prop="guardian">
            <el-input v-model="formData.guardian" placeholder="请输入监护人" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="监护人电话" prop="contact">
            <el-input v-model="formData.contact" maxlength="11" placeholder="请输入监护人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="与监护人关系" prop="guardianPatientRelationship">
            <el-input v-model="formData.guardianPatientRelationship" placeholder="请输入与监护人关系" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="所属管理地区" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择区域"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="现住住址" prop="currentAddress">
            <el-input v-model="formData.currentAddress" maxlength="100" placeholder="请输入现住住址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="包保乡干部" prop="townCadreName">
            <el-input v-model="formData.townCadreName" placeholder="请输入包保乡干部姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="townCadrePhone">
            <el-input
              v-model="formData.townCadrePhone"
              maxlength="11"
              placeholder="请输入包保乡干部电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="包保村干部" prop="villageCadreName">
            <el-input v-model="formData.villageCadreName" placeholder="请输入包保村干部姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="villageCadrePhone">
            <el-input
              v-model="formData.villageCadrePhone"
              maxlength="11"
              placeholder="请输入包保村干部电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="精防医生" prop="doctorName">
            <el-input v-model="formData.doctorName" placeholder="请输入精防医生姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="doctorPhone">
            <el-input
              v-model="formData.doctorPhone"
              maxlength="11"
              placeholder="请输入精防医生电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="包保民警" prop="policeName">
            <el-input v-model="formData.policeName" placeholder="请输入包保民警姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="电话" prop="policePhone">
            <el-input
              v-model="formData.policePhone"
              maxlength="11"
              placeholder="请输入包保民警电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="备注（是否为2025年评定录入人员）" prop="remark" label-width="240px">
            <el-input v-model="formData.remark" maxlength="100" placeholder="备注（是否为2025年评定录入人员）" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
const { t } = useI18n() // 国际化
import { FormRules } from 'element-plus'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as FiveGuaranteesOne from '@/api/patient/fiveGuaranteesOne'
import { debounce } from 'lodash'
defineOptions({ name: 'FiveGuaranteesOneInfoAdd' })
const deptList = ref<Tree[]>([]) // 树形结构
const message = useMessage() // 消息弹窗
const formRef = ref() // 表单 Ref
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const formData = ref({
  patientName: undefined,
  gender: undefined,
  idNumber: undefined,
  currentAddress: undefined,
  birthDate: undefined,
  guardian: undefined,
  contact: undefined,
  deptId: '',
  townCadreName: undefined,
  townCadrePhone: undefined,
  villageCadreName: undefined,
  villageCadrePhone: undefined,
  doctorName: undefined,
  doctorPhone: undefined,
  policeName: undefined,
  policePhone: undefined,
  phone: undefined,
  riskAssessment: undefined,
  guardianPatientRelationship: undefined,
  remark: undefined
})
const dialogTitle = ref('')
const formRules = reactive<FormRules>({
  patientName: [{ required: true, message: '患者姓名不能为空', trigger: 'blur' }],
  gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  guardian: [{ required: true, message: '监护人不能为空', trigger: 'blur' }],
  idNumber: [
    { required: true, message: '身份证不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
          // 如果是修改模式，跳过校验
        if (formType.value === 'action.edit') {
          callback()
          return
        }
        const idCardRegex =
          /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
        if (!idCardRegex.test(value)) {
          callback(new Error('请输入有效的身份证号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  contact: [
    { required: true, message: '联系方式不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(value)) {
          callback(new Error('请输入有效的手机号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
  riskAssessment: [{ required: true, message: '评定的风险等级不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '所属管理地区不能为空', trigger: 'blur' }],
  guardianPatientRelationship: [{ required: true, message: '与监护人关系不能为空', trigger: 'blur' }],
  townCadreName: [{ required: true, message: '包保乡干部姓名不能为空', trigger: 'blur' }],
  townCadrePhone: [{ required: true, message: '包保乡干部电话不能为空', trigger: 'blur' }],
  villageCadreName: [{ required: true, message: '包保村干部姓名不能为空', trigger: 'blur' }],
  villageCadrePhone: [{ required: true, message: '包保村干部电话不能为空', trigger: 'blur' }],
  doctorName: [{ required: true, message: '包保医生姓名不能为空', trigger: 'blur' }],
  doctorPhone: [{ required: true, message: '包保医生电话不能为空', trigger: 'blur' }],
  policeName: [{ required: true, message: '包保民警姓名不能为空', trigger: 'blur' }],
  policePhone: [{ required: true, message: '包保民警电话不能为空', trigger: 'blur' }]
})
watch(
  () => formData.value.idNumber,
  (newIdNumber) => {
    if (newIdNumber && newIdNumber.length === 18) {
      const birthDateStr = newIdNumber.substring(6, 14) // 提取身份证号中的出生日期部分
      const year = birthDateStr.substring(0, 4)
      const month = birthDateStr.substring(4, 6)
      const day = birthDateStr.substring(6, 8)
      const birthDate = new Date(`${year}-${month}-${day}`)
      if (!isNaN(birthDate.getTime())) {
        formData.value.birthDate = birthDate // 自动填写出生日期
      }
    }
  }
)

const initDeptTree = async () => {
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}

const formType = ref('')
/** 打开弹窗 */
const open = async (type: string, id: string) => {
  dialogVisible.value = true
  dialogTitle.value = t(type)
  resetForm()
  if (id != null) {
    formData.value = await FiveGuaranteesOne.getFiveGuauaranteesOneDetail(id)
    formData.value.gender = parseInt(formData.value.gender)
  }
  formType.value = type
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/** 上传成功 */
const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = debounce(async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'action.add') {
      await FiveGuaranteesOne.addFiveGuauaranteesOne(data)
      message.success(t('common.createSuccess'))
    } else {
      //身份证号和出生日期不允许修改
      delete data.idNumber
      delete data.birthDate
      await FiveGuaranteesOne.updateFiveGuauaranteesOne(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}, 300)
onMounted(() => {
  initDeptTree()
})
/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formData.value = {
    patientName: undefined,
    gender: undefined,
    idNumber: undefined,
    currentAddress: undefined,
    birthDate: undefined,
    guardian: undefined,
    contact: undefined,
    deptId: '',
    townCadreName: undefined,
    townCadrePhone: undefined,
    villageCadreName: undefined,
    villageCadrePhone: undefined,
    doctorName: undefined,
    doctorPhone: undefined,
    policeName: undefined,
    policePhone: undefined,
    phone: undefined,
    riskAssessment: undefined,
    guardianPatientRelationship: undefined,
    remark: undefined
  }
  formLoading.value = false
  await nextTick()
}
</script>